<?php
/**
 * <p>Class DB - includes most used functions.</p>
 * <p>Database creating connection, getting resultsets,
 * running sql code and closing connection.</p>
 */
class DB {

    private $link;

    /**
     * Descriptor function
     */
    function DB($dburl, $dbuser, $dbpass, $dbname) {
        $this->connect($dburl, $dbuser, $dbpass, $dbname);
    }

    /**
     * Connect to the database with private credentials
     * found in class DB
     */
    function connect($dburl, $dbuser, $dbpass, $dbname) {
        $link = new mysqli($dburl, $dbuser, $dbpass, $dbname);
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
        $link->query("set character set 'utf8'");
        $link->query("SET NAMES 'utf8'");
        $this->link = $link;
    }

    /**
     * Return resultset from $sql as result
     * @return resource|string
     * @param $sql string Query to run against database
     */
    function resultset($sql) {
        return $this->link->query($sql);
    }

    /**
     * Run query and return array with all of the data
     * @return array[][]
     * @param $sql string Query to run against database
     */
    function resultasarray($sql) {
        $result = $this->resultset($sql);
        $j = 0;
        while($row = $result->fetch_array(MYSQL_BOTH)) {
            for($i=0;$i<count($row);$i++) {
                if(strlen($row[$i])>0)
                    $retarray[$j][$i] = $row[$i];
            }
            $j++;
        }
        return $retarray;
    }

    function gettoprow($sql) {
        $result = $this->resultset($sql);
        return $result->fetch_array();
    }

    /**
     * INSERT and UPDATE sql code
     * @return string|true
     * @param $sql string Query to run against database
     */
    function insert($sql) {
        if(!$this->link->query($sql)) {
            return false;
        }else {
            return true;
        }
    }

    function close() {
        $this->link->close;
    }
}
?>
